import React, { useState, useEffect } from "react";
import { Button, Card, Descriptions, Image } from "antd";
import { useNavigate, useParams } from "react-router-dom";

import { ArrowLeftOutlined } from "@ant-design/icons";
import "./detail.css";
import { connect } from "react-redux";
import axios from "axios";

const Detail = (props) => {
  const navigate = useNavigate();
  let [isLoading, setIsLoading] = useState(true);
  let [productObj, setProductObj] = useState({
    title: "",
    description: "",
    price: "",
    stock: "",
    sales: "",
    cover_url: "",
    details: "",
  });
  const { id } = useParams();
  const { userInfo } = props;

  const reqDetail = async (id) => {
    const responce = await axios.get(
      `http://api.shop.eduwork.cn/api/admin/goods/${id}`,

      {
        headers: {
          Authorization: userInfo.token,
        },
      }
    );

    setIsLoading(false);
    setProductObj(responce.data);
  };

  const reqProObj = () => {
    const newProductObj = props.productList.find((item) => {
      return item.id === id * 1;
    });
    setIsLoading(false);
    setProductObj(newProductObj);
  };

  useEffect(() => {
    if (props.productList.length === 0) {
      reqDetail(id);
    } else {
      reqProObj();
    }

    // eslint-disable-next-line
  }, []);

  return (
    <div className="detail">
      <Card
        title={
          <div className="detail-top">
            <Button
              type="link"
              onClick={() => {
                navigate(-1);
              }}
            >
              <ArrowLeftOutlined style={{ fontSize: "20px" }} />
            </Button>
            <span> 商品详情</span>
          </div>
        }
        loading={isLoading}
      >
        <div className="detail-content">
          <Descriptions bordered style={{ overflow: "auto" }}>
            <Descriptions.Item label="商品名称">
              {productObj.title}
            </Descriptions.Item>
            <Descriptions.Item label="商品图片">
              <Image width={100} src={productObj.cover_url} />
            </Descriptions.Item>
            <Descriptions.Item label="商品描述">
              {productObj.description}
            </Descriptions.Item>
            <Descriptions.Item label="商品价格">
              {productObj.price}
            </Descriptions.Item>
            <Descriptions.Item label="商品库存">
              {productObj.stock}
            </Descriptions.Item>
            <Descriptions.Item label="商品销量">
              {productObj.sales}
            </Descriptions.Item>

            <Descriptions.Item label="商品详情">
              <span
                dangerouslySetInnerHTML={{ __html: productObj.details }}
              ></span>
            </Descriptions.Item>
          </Descriptions>
        </div>
      </Card>
    </div>
  );
};

export default connect((state) => ({
  productList: state.proInfo,
  userInfo: state.userInfo,
}))(Detail);
